package com.md.youyouhui.ui.home;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.md.youyouhui.R;
import com.md.youyouhui.databinding.ActivityOilMealBinding;
import com.md.youyouhui.databinding.AdapterOilPayBinding;
import com.md.youyouhui.net.Constants;
import com.md.youyouhui.net.response.CouponAvailableResponse;
import com.md.youyouhui.net.response.PayMealResponse;
import com.md.youyouhui.ui.BaseActivity;
import com.md.youyouhui.ui.adapter.DataBoundViewHolder;
import com.md.youyouhui.ui.pay.SelectCouponActivity;
import com.md.youyouhui.utils.DialogLoginUtils;
import com.md.youyouhui.utils.MealMinuteDialog;
import com.md.youyouhui.utils.SharedPreferencesUtils;
import com.md.youyouhui.utils.ToastUtils;
import com.md.youyouhui.view.MainViewModel;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by AdministratorZJ
 * on 2019/4/29.
 */
public class MealOilActivity extends BaseActivity {
    private ActivityOilMealBinding mealBinding;
    private int money = 100;
    private String payId;
    private MyAdapter adapter;
    private MainViewModel viewModel;
    private Double discounts;
    private int meal = 0;
    private String months;
    private List<String> numList = new ArrayList<>();
    private List<String> mothList = new ArrayList<>();
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private String id;
    private String couponId;
    private String couponPrice;
    private double savePrice;
    private String token;

    @Override
    public void setContentLayout() {
        mealBinding = DataBindingUtil.setContentView(this, R.layout.activity_oil_meal);
        viewModel = new MainViewModel();
    }

    @Override
    public void initView() {
        setSupportActionBar(mealBinding.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public void initData() {
        token = SharedPreferencesUtils.getString(this, Constants.USER_TOKEN, "");
        mealBinding.payInfoLayout.setOnClickListener(v -> {
            if (TextUtils.isEmpty(months)) {
                return;
            }
            int anInt = Integer.parseInt(months);
            listAdd(anInt, new Date());
            new MealMinuteDialog(MealOilActivity.this, numList, mothList, mealBinding.payMoney.getText().toString()).show();
        });
        mealBinding.payMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    return;
                }
                money = Integer.parseInt(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        adapter = new MyAdapter();
        mealBinding.payRecycler.setAdapter(adapter);
        mealBinding.payAdd.setOnClickListener(v -> {
            money += 100;
            mealBinding.payMoney.setText(String.valueOf(money));
            changePrince();
        });
        mealBinding.payDel.setOnClickListener(v -> {
            if (money <= 100) {
                Toast.makeText(ct, "最少充值100元", Toast.LENGTH_SHORT).show();
                return;
            }
            money -= 100;
            mealBinding.payMoney.setText(String.valueOf(money));
            changePrince();
        });
        mealBinding.payCouponLayout.setOnClickListener(v -> {
            if (TextUtils.isEmpty(token)) {
                new DialogLoginUtils().dialogLogin(this);
                return;
            }
            String all = mealBinding.payAllPrice.getText().toString();
            String[] split = all.split("¥");
            startActivityForResult(new Intent(ct, SelectCouponActivity.class).putExtra("id", id).putExtra("price", split[1]), 101);
        });
        getPayMeal(0, false);
        mealBinding.pay.setOnClickListener(v -> {
            if (TextUtils.isEmpty(months)) {
                Toast.makeText(ct, "请选择套餐", Toast.LENGTH_SHORT).show();
                return;
            }
            Intent intent = new Intent();
            intent.putExtra("money", mealBinding.payMoney.getText().toString());
            intent.putExtra("month", months);
            intent.putExtra("allPrice", mealBinding.payAllPrice.getText().toString());
            intent.putExtra("savePrice", mealBinding.paySave.getText().toString());
            intent.putExtra("id", id);
            intent.putExtra("couponId", couponId);
            setResult(RESULT_OK, intent);
            finish();
        });
    }

    private void getCouponAvailable(String id, String price) {
        viewModel.couponAvailable(id, price).observe(this, couponAvailableResponse -> {
            assert couponAvailableResponse != null;
            switch (couponAvailableResponse.status) {
                case LOADING:
                    mealBinding.progress.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    mealBinding.progress.setVisibility(View.GONE);
                    List<CouponAvailableResponse> data = couponAvailableResponse.data;
                    if (null == data) {
                        return;
                    }
                    mealBinding.payCouponNum.setText(String.format("%d张", data.size()));
                    break;
                case ERROR:
                    mealBinding.progress.setVisibility(View.GONE);
                    ToastUtils.errMake(this, couponAvailableResponse.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == RESULT_OK) {
            if (null == data) {
                return;
            }
            couponId = data.getStringExtra("id");
            couponPrice = data.getStringExtra("price");
            mealBinding.payCouponNum.setText(String.format("%s元", couponPrice));
            /*String all = mealBinding.payAllPrice.getText().toString();
            String[] split = all.split("¥");
            //原总价减去优惠券
            Double price = Double.parseDouble(split[1]) - Double.parseDouble(couponPrice);
            mealBinding.payAllPrice.setText("¥" + price);
            double savePrices = savePrice + Double.parseDouble(couponPrice);
            mealBinding.paySave.setText("(省" + savePrices + ")");*/
            getPayMeal(Double.parseDouble(couponPrice), true);
        }
    }

    void listAdd(int months, Date date) {
        numList.clear();
        mothList.clear();
        for (int i = 0; i < months; i++) {
            numList.add(String.valueOf(i + 1));
            calendar.setTime(date);
            if (months == 1) {
                calendar.add(Calendar.MONTH, i + 1);
            } else {
                calendar.add(Calendar.MONTH, i);
            }
            Date time = calendar.getTime();
            mothList.add(sdf.format(time));
        }
    }

    private void getPayMeal(double couponPrice, boolean isSelect) {
        viewModel.payMeal(1, 10).observe(this, payMealResponse -> {
            assert payMealResponse != null;
            switch (payMealResponse.status) {
                case LOADING:
                    mealBinding.progress.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    mealBinding.progress.setVisibility(View.GONE);
                    PayMealResponse data = payMealResponse.data;
                    if (null == data) {
                        return;
                    }
                    List<PayMealResponse.Rows> rows = data.rows;
                    adapter.upDate(rows);
                    allPrince(rows.get(meal).discount, rows.get(meal).months, couponPrice);
                    discounts = rows.get(meal).discount;
                    months = rows.get(meal).months;
                    id = rows.get(meal).id;
                    /*String all = mealBinding.payAllPrice.getText().toString();
                    String[] split = all.split("¥");
                    if (!isSelect) {
                        //没有选择优惠券，还是显示有多少张优惠券
                        getCouponAvailable(id, split[1]);
                    }*/
                    break;
                case ERROR:
                    mealBinding.progress.setVisibility(View.GONE);
                    ToastUtils.errMake(this, payMealResponse.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    class MyAdapter extends RecyclerView.Adapter<DataBoundViewHolder<AdapterOilPayBinding>> {
        List<PayMealResponse.Rows> rows;
        Double couponMoney;

        public void upDate(List<PayMealResponse.Rows> rows) {
            this.rows = rows;
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public DataBoundViewHolder<AdapterOilPayBinding> onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            AdapterOilPayBinding binding = DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()), R.layout.adapter_oil_pay, viewGroup, false);
            return new DataBoundViewHolder<>(binding);
        }

        @Override
        public void onBindViewHolder(@NonNull DataBoundViewHolder<AdapterOilPayBinding> holder, int i) {
            if (meal == i) {
                holder.binding.payBg.setBackgroundResource(R.drawable.add_yellow_bg);
                holder.binding.payOut.setEnabled(true);
                holder.binding.payZhekou.setEnabled(true);
                holder.binding.payZhekouDel.setEnabled(true);
                holder.binding.line.setBackgroundColor(getResources().getColor(R.color.white));
            } else {
                holder.binding.payBg.setBackgroundResource(R.drawable.add_blank_bg);
                holder.binding.payOut.setEnabled(false);
                holder.binding.payZhekou.setEnabled(false);
                holder.binding.payZhekouDel.setEnabled(false);
                holder.binding.line.setBackgroundColor(getResources().getColor(R.color.main_color));
            }
            if ("0".equals(rows.get(i).activityTag)) {
                holder.binding.layoutTag.setVisibility(View.GONE);
            } else {
                holder.binding.layoutTag.setVisibility(View.VISIBLE);
                if ("1".equals(rows.get(i).activityTag)) {
                    holder.binding.payTag.setText("热销");
                } else if ("2".equals(rows.get(i).activityTag)) {
                    holder.binding.payTag.setText("抢购");
                } else if ("3".equals(rows.get(i).activityTag)) {
                    holder.binding.payTag.setText("专享");
                } else if ("4".equals(rows.get(i).activityTag)) {
                    holder.binding.payTag.setText("超值");
                } else if ("5".equals(rows.get(i).activityTag)) {
                    holder.binding.payTag.setText("限时");
                }
            }
            String discount = String.valueOf(rows.get(i).discount);
            String value = String.valueOf(rows.get(i).originalDiscount);
            double discoun = Math.rint(Float.parseFloat(discount) * 1000) / 100;
            double valu = Math.rint(Float.parseFloat(value) * 1000) / 100;
            BigDecimal bigDecimal = new BigDecimal(discount);
            BigDecimal bigValue = new BigDecimal(value);
            BigDecimal bigDecimal1 = new BigDecimal("10");
            BigDecimal multiply = bigDecimal.multiply(bigDecimal1);
            BigDecimal multiplyValue = bigValue.multiply(bigDecimal1);
            BigDecimal decimal = multiply.setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal originalDiscount = multiplyValue.setScale(2, BigDecimal.ROUND_HALF_UP);
            holder.binding.payZhekou.setText(discoun + "折");
            holder.binding.payOut.setText(String.format("%s个月已售%s", rows.get(i).months, rows.get(i).sold));
            holder.binding.payZhekouDel.setText(valu + "折");
            holder.itemView.setOnClickListener(v -> {
                couponPrice = "";
                couponId = "";
                mealBinding.payCouponNum.setText(couponPrice);
                meal = i;
                discounts = rows.get(i).discount;
                months = rows.get(i).months;
                id = rows.get(i).id;
                notifyDataSetChanged();
                if (TextUtils.isEmpty(couponPrice)) {
                    couponMoney = 0.0;
                } else {
                    couponMoney = Double.parseDouble(couponPrice);
                }
                allPrince(rows.get(i).discount, rows.get(i).months, couponMoney);

                /*String all = mealBinding.payAllPrice.getText().toString();
                String[] split = all.split("¥");
                getCouponAvailable(id, split[1]);*/
            });
        }

        @Override
        public int getItemCount() {
            return null == rows ? 0 : rows.size();
        }
    }

    void allPrince(Double discountPrice, String months, double couponPrice) {
        if (TextUtils.isEmpty(months)) {
            return;
        }
        mealBinding.payMonth.setText(String.format("%s个月", months));
        String money = mealBinding.payMoney.getText().toString();
        int moneyS = Integer.parseInt(money) * Integer.parseInt(months);
        mealBinding.payYuanPrice.setText("充值" + months + "个月原价" + moneyS + "元,折扣价");
        double newPrice = moneyS * discountPrice;
        newPrice = (double) Math.round(newPrice * 10) / 10;
        savePrice = moneyS - newPrice;
        //套餐总价
        mealBinding.payNewPrice.setText(newPrice + "元,省" + savePrice);
        //算上优惠券，所有的价格
        double allPrice = newPrice - couponPrice;
        savePrice += couponPrice;
        mealBinding.payAllPrice.setText("¥" + allPrice);
        mealBinding.paySave.setText("(省" + savePrice + ")");
    }

    void changePrince() {
        if (TextUtils.isEmpty(months)) {
            return;
        }
        mealBinding.payMonth.setText(String.format("%s个月", months));
        String money = mealBinding.payMoney.getText().toString();
        int moneyS = Integer.parseInt(money) * Integer.parseInt(months);
        mealBinding.payYuanPrice.setText("充值" + months + "个月原价" + moneyS + "元,折扣价");
        double newPrice = moneyS * discounts;
        newPrice = (double) Math.round(newPrice * 10) / 10;
        savePrice = moneyS - newPrice;
        mealBinding.payNewPrice.setText(newPrice + "元,省" + savePrice);
        //算上优惠券，所有的价格
        if (TextUtils.isEmpty(couponPrice)) {
            mealBinding.payAllPrice.setText("¥" + newPrice);
            mealBinding.paySave.setText("(省" + savePrice + ")");
        } else {
            double parseDouble = Double.parseDouble(couponPrice);
            double allPrice = newPrice - parseDouble;
            savePrice += parseDouble;
            mealBinding.payAllPrice.setText("¥" + allPrice);
            mealBinding.paySave.setText("(省" + savePrice + ")");
        }
    }
}
